# 前端组件化

# 一、模板引擎

# 目录结构

src/
├── layouts/
│   └── main.pug       # 主布局模板
├── partials/          # 公共组件
│   ├── header.pug
│   ├── sidebar.pug
│   └── footer.pug
└── pages/
    └── dashboard.pug  # 业务页面

# 代码示例

//- 主布局模板(layouts/main.pug)
doctype html
html
  head
    title= title
    include ../partials/header
  body
    include ../partials/sidebar
    block content
    include ../partials/footer

//- 业务页面(pages/dashboard.pug)
extends ../layouts/main.pug
block content
  h1 控制面板
  //- 页面专属内容

# 二、静态网站生成器

Jekyll 实现示例:

<!-- 布局模板(_layouts/default.html) -->
<html>
  {% include header.html %}
  <body>{{ content }}</body>
</html>

<!-- 组件(_includes/header.html) -->
<nav class="main-header">
  {{ site.title }} <!-- 动态配置注入 -->
</nav>

# 三、前端框架组件化

# SPA 开发模式

<!-- Vue3 + AdminLTE示例 -->
<template>
  <AdminLayout>
    <Sidebar :menuItems="menu"/>
    <Header :user="currentUser"/>
    <router-view/> <!-- 动态内容区 -->
  </AdminLayout>
</template>

# SSR 框架整合

Next.js (opens new window) | Nuxt.js (opens new window)

同时支持组件化与服务端渲染,替代传统模板方案。

# 四、服务端模板

# PHP 方案

<?php
// 引入公共头部
include('partials/header.php');
?>

<div class="content">
  <?php if($isAdmin): ?>
    <admin-panel/>
  <?php endif; ?>
</div>

<?php include('partials/footer.php'); ?>

# Node.js 方案

Express + EJS

// app.js 配置视图引擎
app.set('view engine', 'ejs');

// routes.js 路由渲染
router.get('/', (req, res) => {
  res.render('dashboard', { title: '控制台' });
});

# 五、HTML 引入

# 浏览器原生方案

<object
  type="text/html"
  data="sidebar.html"
  style="width:100%">
</object>

# 服务端包含

服务器端包含(Server Side Include,SSI)

<!-- 需配置Nginx/Apache支持 -->
<!-- #include virtual="/partials/header.html" -->

# Reference